package paylayer

import (
	"strconv"
	"strings"
	"dhfshop/models/misc"
	"encoding/json"
	"dhfshop/models/isv"
	"dhfshop/utils/math"
	"dhfshop/models/shopping"
	"github.com/astaxie/beego"
	"thirdpaysdk/api/hnapay"
	"dhfshop/service/redisgo"
	"dhfshop/utils/uuid"
)

func OrderHnaPay(appId,openId string,acPay *isv.AcPayParams,order *shopping.ValueOrder)(rsp PayResponse,prepayId string, err error) {
	itemsTitle := "测试商品"
	uniqueId, _ := uuid.GetSnowFlakeId(uuid.Worker)
	uniqueIdStr := strconv.FormatInt(uniqueId, 10)
	orderIdStr := strconv.FormatInt(order.OrderId, 10)
	var payInfoCache *PayInfoCache = new(PayInfoCache)
	cacheKey := "payorder_" + orderIdStr
	redisconn := redisgo.GetInstance()
	/*
	if cacheValue, e := redisconn.GetString(cacheKey); e == nil && len(cacheValue) > 5  {
		if err = json.Unmarshal([]byte(cacheValue), payInfoCache); err == nil {
			rsp.WxpayRsp = payInfoCache.SignInfo
	        rsp.OrderId = orderIdStr
			return
		}
	}
	*/
	if orderItemTitles, e := shopping.GetItemsTitle(order.OrderId); e == nil {
	   if len(orderItemTitles) > 3 {
	      itemsTitle = orderItemTitles
	   }
	}
	merCode := acPay.SubMchId
	secreCode := acPay.Appkey
	currency := acPay.MediaId
	notifyUrl := beego.AppConfig.String("WXPayNotify") + "/public/hnapay/notify"
	var payment int = int(math.MultiTotalPriceInt(order.Payment, 100))
	profitSharing, err := GetHnapayShareFlag(acPay.SubAppId,order.StoreId)
	beego.Debug("GetWxAppCfg profitSharing:", profitSharing)
	//
	m := &shopping.ValueOrder{OrderId:order.OrderId,ProfitStatus:0}
	if profitSharing == "2" {
	   m.ProfitStatus = 1
	}
	shopping.UpdateOrderProfit(m)
	
	payInfo, e := hnapay.MicroAppPay(merCode,uniqueIdStr,orderIdStr,"大黄蜂科技",itemsTitle,1,int(payment),currency,"0001","5",profitSharing,notifyUrl,secreCode,openId)
	if e != nil {
		beego.Debug(e.Error())
		err = e
		return 
	}
	prepayId = strings.Replace(payInfo.Package, "prepay_id=", "", -1)
	//更新订单支付方式编号
	order.PayWayCode = 20
	err = shopping.UpdateOrderPayWayCodeByOrderId(order.OrderId, order.PayWayCode)
	if err != nil {
		beego.Debug(err.Error())
	}
	payRsp := misc.WxResponse{}
	payRsp.AppId = payInfo.AppId
	payRsp.NonceStr = payInfo.NonceStr
	payRsp.Package = payInfo.Package
	payRsp.SignType = payInfo.SignType
	payRsp.TimeStamp = payInfo.TimeStamp
	payRsp.PaySign = payInfo.PaySign
	if tempJson, err := json.Marshal(payRsp); err == nil { 
	   rsp.WxpayRsp = string(tempJson)
	   rsp.OrderId = orderIdStr
	}
	payInfoCache.AppId = appId
	payInfoCache.MchId = acPay.MchId
	payInfoCache.AppKey = acPay.Appkey
	payInfoCache.OrderKind = "ESHOP_ORDER_PAY"
	payInfoCache.SignInfo = rsp.WxpayRsp
	if payInfoJSON, err := json.Marshal(payInfoCache); err == nil { 
		if _, err = redisconn.Set(cacheKey, string(payInfoJSON), 72*60*60); err != nil {  
			beego.Debug("SETEX", err.Error())
		}
	}
	return
}

func ChargeHnaPay(appId,openId,outTradeNo string,acPay *isv.AcPayParams,amount float32)(rsp PayResponse,prepayId string,err error){
	uniqueId, _ := uuid.GetSnowFlakeId(uuid.Worker)
	uniqueIdStr := strconv.FormatInt(uniqueId, 10)
	//
	merCode := acPay.SubMchId
	secreCode := acPay.Appkey
	currency := acPay.MediaId
	notifyUrl := beego.AppConfig.String("WXPayNotify") + "/public/hnapay/notify"
	payment := math.MultiTotalPriceInt(amount, 100)
	payInfo, e := hnapay.MicroAppPay(merCode,uniqueIdStr,outTradeNo,"大黄蜂科技","账户充值",1,int(payment),currency,"0001","5","0",notifyUrl,secreCode,openId)
	if e != nil {
		beego.Debug(e.Error())
		err = e
		return 
	}
	prepayId = strings.Replace(payInfo.Package, "prepay_id=", "", -1)
	payRsp := misc.WxResponse{}
	payRsp.AppId = payInfo.AppId
	payRsp.NonceStr = payInfo.NonceStr
	payRsp.Package = payInfo.Package
	payRsp.SignType = payInfo.SignType
	payRsp.TimeStamp = payInfo.TimeStamp
	payRsp.PaySign = payInfo.PaySign
	if tempJson, err := json.Marshal(payRsp); err == nil {
		rsp.WxpayRsp = string(tempJson)
	}
	redisconn := redisgo.GetInstance()
	cacheKey := "payorder_" + outTradeNo
	var payInfoCache *PayInfoCache = new(PayInfoCache)
	payInfoCache.AppId = appId
	payInfoCache.MchId = acPay.MchId
	payInfoCache.AppKey = acPay.Appkey
	payInfoCache.OrderKind = "MEMBER_CHARGE"
	if payInfoJSON, err := json.Marshal(payInfoCache); err == nil { 
		if _, err = redisconn.Set(cacheKey, string(payInfoJSON), 72*60*60); err != nil {  
			beego.Debug("SETEX", err.Error())
		}
	}
	return
}

func CommonHnaPay(appId,openId,orderId,body,kind string,acPay *isv.AcPayParams,amount float32)(rsp PayResponse,prepayId string, err error){
	uniqueId, _ := uuid.GetSnowFlakeId(uuid.Worker)
	uniqueIdStr := strconv.FormatInt(uniqueId, 10)
	merCode := acPay.SubMchId
	secreCode := acPay.Appkey
	currency := acPay.MediaId
	notifyUrl := beego.AppConfig.String("WXPayNotify") + "/public/hnapay/notify"
	payment := math.MultiTotalPriceInt(amount, 100)
	payInfo, e := hnapay.MicroAppPay(merCode,uniqueIdStr,orderId,"大黄蜂科技","通用支付",1,int(payment),currency,"0001","5","0",notifyUrl,secreCode,openId)
	if e != nil {
		beego.Debug(e.Error())
		err = e
		return 
	}
	prepayId = strings.Replace(payInfo.Package, "prepay_id=", "", -1)
	payRsp := misc.WxResponse{}
	payRsp.AppId = payInfo.AppId
	payRsp.NonceStr = payInfo.NonceStr
	payRsp.Package = payInfo.Package
	payRsp.SignType = payInfo.SignType
	payRsp.TimeStamp = payInfo.TimeStamp
	payRsp.PaySign = payInfo.PaySign
	if tempJson, err := json.Marshal(payRsp); err == nil { 
	   rsp.WxpayRsp = string(tempJson)
	}
	redisconn := redisgo.GetInstance()
	cacheKey := "payorder_" + orderId
	var payInfoCache *PayInfoCache = new(PayInfoCache)
	payInfoCache.AppId = appId
	payInfoCache.MchId = acPay.MchId
	payInfoCache.AppKey = acPay.Appkey
	payInfoCache.OrderKind = kind
	if payInfoJSON, err := json.Marshal(payInfoCache); err == nil { 
		if _, err = redisconn.Set(cacheKey, string(payInfoJSON), 72*60*60); err != nil {  
			beego.Debug("SETEX", err.Error())
		}
	}
	return
}

func GetHnapayShareFlag(appId string,storeId int64)(string, error){
	var profitSharing string = "0"
	cfg, err := misc.GetWxAppCfgByAppIdAndNameAndStoreId(appId,"CONFIG-FENZHANG",storeId); if err == nil {
	    var dat map[string]int
		dat = make(map[string]int)
		beego.Debug("cfg.Value:", cfg.Value)
        if err = json.Unmarshal([]byte(cfg.Value), &dat); err != nil {
		   return profitSharing, err
		}
	    for k, v := range dat {
		  storeIdStr := strconv.FormatInt(storeId, 10)
		  if storeIdStr == k && v == 1{
			 profitSharing = "2"
		  }
	    }
	}
	return profitSharing, nil
}

